﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Simple.Tools;
using System.Text;
using BaseMessage = Simple.Common.BaseMessage;

namespace Simple.Web.Common
/// <summary>
/// 版 本 钢易智企2.0 V 2.0.0 钢易智企2.0
/// Copyright (c) 2023 杭州钢易科技有限公司
/// 创建人：曾东明
/// 日 期：2024
/// 描 述：
/// </summary>
{
    public class SimpleExceptionAttributer : ExceptionFilterAttribute
    {
        private ILogger<SimpleExceptionAttributer> logger;
        private IModelMetadataProvider modelMetadataProvider;

        [Autowired]
        protected IWebHostEnvironment environment { get; set; }

        public SimpleExceptionAttributer(ILogger<SimpleExceptionAttributer> logger, IModelMetadataProvider modelMetadataProvider, IWebHostEnvironment environment)
        {
              this.logger = logger;
              this.modelMetadataProvider = modelMetadataProvider;
              this.environment = environment;

        }
        public override void OnException(ExceptionContext context)
        {
            StringBuilder messageInfomations = new StringBuilder();

            string msg=string.Empty;
            GetErrorMeesage(context.Exception,messageInfomations);

			if (environment.IsDevelopment())
            {
				msg= messageInfomations.ToString();
			}
            else
            {
                  msg="服务器异常,请联系管理员!";
			}
            logger.LogError(messageInfomations.ToString());
            if (!context.ExceptionHandled)
            {
                context.Result = new JsonResult(new BaseMessage(msg,500));
            }
            base.OnException(context);
        }
        private void GetErrorMeesage(Exception ex,StringBuilder message)
        {
            if (ex != null)
            {
				message.Append("message\t:\t"+ex.Message);
				message.Append("stackTrace\t:\t" + ex.StackTrace);
                if (ex.InnerException != null)
                {
					GetErrorMeesage(ex.InnerException,message);
                }
            }
        }
    }
}
